<template>
  <div class="maps">
    <div class="info">
      <div class="searchs">
        <Input
          v-model="searchObj.local"
          placeholder="请输入位置地点名称"
          class="local"
          @on-clear="clearLocal"
          clearable
          suffix="ios-search"
          @on-keyup="searchLocation"
          @blur="blur"
        ></Input>
        <div class="bg">
          <transition mode="out-in" name="el-zoom-in-top">
            <div v-show="show" class="card">
              <div
                class="item"
                v-for="(item, index) in searchList"
                :key="index"
                :title="item.address"
                @click="doPosition(item)"
              >
                <span class="title">{{ item.title }}</span>
                <span class="address">{{ item.address }}</span>
              </div>
            </div>
          </transition>
        </div>
      </div>
      <Input
        class="coordinate"
        v-model="searchObj.coordinate"
        readonly
        placeholder="坐标位置"
        @click.native="doCopy"
        :title="searchObj.coordinate"
      ></Input>
    </div>
    <div id="container" style="width:670px; height:400px;"></div>
  </div>
</template>

<script>
import $ from 'jquery'
var map
var marker
var searchService
var markersArray = []
export default {
  name: 'maps',
  props: {
    address: {
      type: String,
      default: () => ''
    },
    position: {
      type: String,
      default: () => ''
    }
  },
  data () {
    return {
      searchObj: {
        coordinate: ''
      },
      searchList: [],
      show: false
    }
  },

  mounted () {
    // 初始化地图
    this.$nextTick(() => {
      this.initTxMap(this.position)
      // 回显坐标位置
      console.log(this.position, '-----this.position')
      if (this.position) {
        this.searchObj.coordinate = '坐标：' + this.position
      }
    })
  },
  watch: {
    searchList: {
      handler (cur, prev) {
        if (cur) {
          if (cur.length > 0) {
            this.show = true
          } else {
            this.show = false
          }
        } else {
          this.show = false
        }
      },
      deep: true,
      immediate: true,
      title: ''
    }
  },
  methods: {
    blur () {
      this.searchList = []
      this.show = false
    },
    searchLocation (result) {
      var that = this
      $.ajax({
        url: `https://apis.map.qq.com/ws/place/v1/suggestion/?keyword=${this.searchObj.local}&key=U7TBZ-NRB6Q-27D55-GXCSD-T3WNK-DMFQI&output=jsonp&region_fix=1`,
        type: 'get',
        dataType: 'jsonp',
        success (res) {
          that.$nextTick(() => {
            that.searchList = res.data
          })
        }
      })
    },
    // 初始化腾讯地图
    initTxMap (position) {
      var that = this
      console.log(position, '----position')
      if (position) {
        var centerArr = position.split(',')
        var center = new qq.maps.LatLng(centerArr[1], centerArr[0])
        map = new qq.maps.Map(document.getElementById('container'), {
          center: center, // 设置地图中心点坐标
          zoom: 16, // 设置地图缩放级别
          pitch: 43.5, // 设置俯仰角
          rotation: 45 // 设置地图旋转角度
        })
        marker = new qq.maps.Marker({
          position: center,
          animation: qq.maps.MarkerAnimation.BOUNCE,
          map: map
        })
        var infos
        // 添加监听事件  获取鼠标点击事件
        qq.maps.event.addListener(map, 'click', function (event) {
          $.ajax({
            url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${
              event.latLng.lat + ',' + event.latLng.lng
            }&key=U7TBZ-NRB6Q-27D55-GXCSD-T3WNK-DMFQI&get_poi=1&output=jsonp`,
            type: 'get',
            dataType: 'jsonp',
            success (res) {
              var center = new qq.maps.LatLng(
                event.latLng.lat,
                event.latLng.lng
              )
              if (infos) {
                infos.close()
              }
              infos = new qq.maps.InfoWindow({
                map: map
              })
              infos.open()
              infos.setContent(
                '<div class="infoWindow">' + res.result.address + '</div>'
              )
              that.$emit('update:address', res.result.address)
              infos.setPosition(center)
            }
          })
          // 逆解析展示infoWindow
          if (!marker) {
            marker = new qq.maps.Marker({
              position: event.latLng,
              animation: qq.maps.MarkerAnimation.BOUNCE,
              map: map
            })
            return
          }
          const location = `${(event.latLng.lng * 1).toFixed(6)},${(
            event.latLng.lat * 1
          ).toFixed(6)}`
          that.searchObj.coordinate = `坐标：${location}`
          that.$emit('update:position', location)
          marker.setPosition(event.latLng)
        })
        // 绑定搜索事件
        that.bindSearch()
      } else {
        $.ajax({
          type: 'get',
          url: 'https://apis.map.qq.com/ws/location/v1/ip?key=U7TBZ-NRB6Q-27D55-GXCSD-T3WNK-DMFQI&output=jsonp',
          dataType: 'jsonp',
          success: function (res) {
            const { result } = res
            console.log(result.location.lat, result.location.lng)
            var center = new qq.maps.LatLng(
              result.location.lat,
              result.location.lng
            )
            map = new qq.maps.Map(document.getElementById('container'), {
              center: center, // 设置地图中心点坐标
              zoom: 16, // 设置地图缩放级别
              pitch: 43.5, // 设置俯仰角
              rotation: 45 // 设置地图旋转角度
            })
            marker = new qq.maps.Marker({
              position: center,
              animation: qq.maps.MarkerAnimation.BOUNCE,
              map: map
            })
            var infos
            // 添加监听事件  获取鼠标点击事件
            qq.maps.event.addListener(map, 'click', function (event) {
              $.ajax({
                url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${
                  event.latLng.lat + ',' + event.latLng.lng
                }&key=U7TBZ-NRB6Q-27D55-GXCSD-T3WNK-DMFQI&get_poi=1&output=jsonp`,
                type: 'get',
                dataType: 'jsonp',
                success (res) {
                  var center = new qq.maps.LatLng(
                    event.latLng.lat,
                    event.latLng.lng
                  )
                  if (infos) {
                    infos.close()
                  }
                  infos = new qq.maps.InfoWindow({
                    map: map
                  })
                  infos.open()
                  infos.setContent(
                    '<div class="infoWindow">' + res.result.address + '</div>'
                  )
                  that.$emit('update:address', res.result.address)
                  infos.setPosition(center)
                }
              })
              if (!marker) {
                marker = new qq.maps.Marker({
                  position: event.latLng,
                  animation: qq.maps.MarkerAnimation.BOUNCE,
                  map: map
                })
                return
              }
              const location = `${(event.latLng.lng * 1).toFixed(6)},${(
                event.latLng.lat * 1
              ).toFixed(6)}`
              that.searchObj.coordinate = `坐标：${location}`
              that.$emit('update:position', location)
              marker.setPosition(event.latLng)
            })
            // 绑定搜索事件
            that.bindSearch()
          }
        })
      }
    },
    clearLocal () {
      this.searchObj = this.$options.data().searchObj
      this.searchList = []
    },
    clears () {
      this.searchObj = this.$options.data().searchObj
    },
    doPosition (item) {
      const location = `${(item.location.lng * 1).toFixed(6)},${(
        item.location.lat * 1
      ).toFixed(6)}`
      this.searchObj.coordinate = `坐标：${location}`
      this.searchObj.local = item.title
      this.$emit('update:position', location)
      if (markersArray) {
        for (var i in markersArray) {
          markersArray[i].setMap(null)
        }
      }
      this.title = item.title
      searchService.search(this.title)
      this.show = false
    },
    bindSearch () {
      var that = this
      var info
      searchService = new qq.maps.SearchService({
        complete: function (results) {
          if (results.type === 'CITY_LIST') {
            searchService.setLocation(results.detail.cities[0].cityName)
            searchService.search(that.title)
            return
          }
          var pois = results.detail.pois
          var latlngBounds = new qq.maps.LatLngBounds()
          for (var i = 0, l = pois.length; i < l; i++) {
            var poi = pois[i]
            latlngBounds.extend(poi.latLng)
            var marker = new qq.maps.Marker({
              map: map,
              position: poi.latLng
            })
            markersArray.push(marker)
            marker.setTitle(poi.name)
            qq.maps.event.addListener(marker, 'click', function (e) {
              if (info) {
                info.close()
              }
              const location = `${(e.latLng.lng * 1).toFixed(6)},${(
                e.latLng.lat * 1
              ).toFixed(6)}`
              var center = new qq.maps.LatLng(e.latLng.lat, e.latLng.lng)
              that.searchObj.coordinate = `坐标：${location}}`
              that.$emit('update:position', location)
              info = new qq.maps.InfoWindow({
                map: map
              })
              info.open()
              info.setContent(
                '<div class="infoWindow">' + e.target.title + '</div>'
              )
              info.setPosition(center)
            })
          }
          map.fitBounds(latlngBounds)
        }
      })
    },
    doCopy () {
      // 先全局销毁
      this.$Message.destroy()
      var input = document.createElement('input')
      var value = document.querySelector('.coordinate input').value
      input.value = value
      document.querySelector('.addApplication').appendChild(input)
      input.select()
      document.execCommand('Copy')
      input.remove()
      this.$Message.success('复制成功')
    }
  }
}
</script>

<style lang="scss" scoped>
.maps ::v-deep {
  position: relative;
  .infoWindow {
    min-width: 100px;
  }
  .info {
    z-index: 999;
    width: auto;
    width: 500px;
    // padding: 10px;
    margin-left: 70px;
    position: absolute;
    top: 20px;
    // border-radius: 0.25rem;
    font-size: 14px;
    color: #666;
    display: flex;
    gap: 0 20px;
    align-items: center;
    .local {
      width: 250px;
    }
    .coordinate {
      width: 200px;
    }
    .searchs {
      position: relative;
      .bg {
        padding: 10px 0;
        position: absolute;
        top: 35px;
        .card {
          background-color: #fff;
          box-shadow: 0 0 5px 0 grey;
          border-radius: 5px;
          .item {
            display: flex;
            justify-content: space-between;
            padding: 0 10px;
            gap: 0 10px;
            cursor: pointer;
            &:last-child {
              border-radius: 0 0 5px 5px;
            }
            &:first-child {
              border-radius: 5px 5px 0 0;
            }
            &:hover {
              background: rgb(232, 232, 245);
            }
            .title {
              width: 140px;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }
            .address {
              width: 160px;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
            }
          }
        }
      }
    }
    // box-shadow: 0 2px 6px 0 rgba(27, 142, 236, 0.5);
  }
}
</style>
